package com.sky.controller.user;

import com.sky.entity.AddressBook;
import com.sky.result.Result;
import com.sky.service.AddressBookService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@RestController
@RequestMapping("/user/addressBook")
public class AddressBookController {

    @Autowired
    private AddressBookService addressBookService;

    //新增地址
    @PostMapping
    public Result addAddress(@RequestBody AddressBook addressBook){
        addressBookService.addAddress(addressBook);
        return Result.success();
    }

    //查询所有地址
    @GetMapping("/list")
    public Result<List<AddressBook>> listAddress(){
        List<AddressBook> addressBooks = addressBookService.listAddress();
        return Result.success(addressBooks);
    }

    //查询默认地址
    @GetMapping("/default")
    public Result<AddressBook> defaultAddress(){
        List<AddressBook> addressBook = addressBookService.defaultAddress();
        if (addressBook != null && addressBook.size() == 1) {
            return Result.success(addressBook.get(0));
        }
        return Result.error("没有查询到默认地址");
    }


    //根据ID修改地址
    @PutMapping
    public Result updateAddress(@RequestBody AddressBook addressBook){
        addressBookService.updateAddress(addressBook);
        return Result.success();
    }

    //根据ID删除地址
    @DeleteMapping
    public Result deleteAddress(@RequestParam Long id){
        addressBookService.deleteAddress(id);
        return Result.success();
    }

    //根据ID查询地址
    @GetMapping("{id}")
    public Result<AddressBook> getAddress(@PathVariable Long id){
        AddressBook addressBook = addressBookService.getAddress(id);
        return Result.success(addressBook);
    }

    //设置默认地址
    @PutMapping("/default")
    public Result setDefaultAddress(@RequestBody AddressBook addressBook){
        addressBookService.setDefaultAddress(addressBook);
        return Result.success();
    }


}
